#!/bin/sh
#
# Copyright 2018-2021 Balena Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit

. /usr/sbin/balena-config-vars
. /usr/bin/rollback-parse-bootloader

echo "Rollback: Stopping further rollbacks"
echo "Rollback: Setting upgrade_available to 0 and removing breadcrumbs"
rm -f /mnt/state/rollback-health-variables || true
rm -f /mnt/state/rollback-altboot-breadcrumb || true
rm -f /mnt/state/rollback-health-breadcrumb || true
rm -f /mnt/state/rollback-health-failed || true
rm -f "${BALENA_NONENC_BOOT_MOUNTPOINT}/bootcount.env" || true
for ENV_FILE_NAME in bootenv grubenv; do
	ENV_FILE=$(find -L "${BALENA_NONENC_BOOT_MOUNTPOINT}" -name "${ENV_FILE_NAME}")
	if [ -f "${ENV_FILE}" ]; then
		"${CAT}" "${ENV_FILE}" | sed "s#bootcount=.*#bootcount=0 #g" | "${WR}" "${ENV_FILE}" || true
	fi
done
sync -f /mnt/state
sync -f "${BALENA_NONENC_BOOT_MOUNTPOINT}"

echo "Rollback: Following bootloader file ${BOOTLOADER_FILE} found"
if [ -f "${BOOTLOADER_FILE}" ]; then
	"${CAT}" "${BOOTLOADER_FILE}" | sed "s#upgrade_available=.*#upgrade_available=0#g" | "${WR}" "${BOOTLOADER_FILE}"
fi

sync -f "${BALENA_NONENC_BOOT_MOUNTPOINT}"
echo "Rollback: Further rollbacks stopped"
